<template>
  <div style="width: 100%; height: 100vh; background-color: darkslateblue; overflow: hidden">
    <div style="width: 400px; margin: 150px auto">
      <div style="color: #cccccc; font-size: 30px; text-align: center; padding:30px 0">欢迎登录</div>
      <el-form ref="form" :model="form" size="normal" :rules="rules">
        <el-form-item prop="username">
          <el-input v-model="form.username">
            <template #prefix>
              <el-icon class="el-input__icon">
                <Avatar/>
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="form.password" show-password>
            <template #prefix>
              <el-icon class="el-input__icon">
                <Lock/>
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button style="width: 100%" type="primary" @click="login">登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import {Lock, Avatar} from '@element-plus/icons'
import {ElMessage} from "element-plus";
import request from "../../utils/request";

export default {
  name: "Login",
  components: {
    Lock,
    Avatar,
  },
  data() {
    return {
      form: {},
      rules: {
        username: [
          {
            required: true,
            message: '请输入用户名',
            trigger: 'blur',
          },
        ],
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur',
          },
        ],
      },
    }
  },
  methods: {
    login() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          request.post("/user/login", this.form).then(res => {
            if (res.code === '0') {
              ElMessage({
                showClose: true,
                type: "success",
                message: "登录成功",
              })
              sessionStorage.setItem("user",JSON.stringify(res.data)) //缓存用户信息
              this.$router.push("/")  //登录成功之后进行页面跳转，跳转到主页
            } else {
              ElMessage({
                showClose: true,
                type: "error",
                message: "登录失败," + res.msg,
              })
            }
          })
        }
      })
    }
  }
}
</script>

<style scoped>

</style>